package free.mrchen.boot.gate.server.def;

import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;

import java.net.URI;
import java.util.stream.Collectors;

public class RouteDefConvert {

    public static RouteDefinition toDefinition( RouteDef def ) {
        RouteDefinition definition = new RouteDefinition();
        definition.setUri(URI.create( def.getUri() ));
        definition.setId( def.getId() );
        definition.setOrder( def.getOrder() );
        definition.getMetadata().putAll( def.getMetadata() );
        for (String predicate : def.getPredicates()) {
            definition.getPredicates().add( new PredicateDefinition(predicate));
        }
        for (String filter : def.getFilters()) {
            definition.getFilters().add( new FilterDefinition(filter) );
        }
        return definition;
    }

    public static RouteDef toDef( RouteDefinition definition ) {
        RouteDef def = new RouteDef();
        def.setId( definition.getId() );
        def.setOrder(definition.getOrder() );
        def.setUri( definition.getUri().toString() );
        def.getMetadata().putAll( definition.getMetadata() );
        for (PredicateDefinition predicate : definition.getPredicates()) {
            def.getPredicates().add( stringDef( predicate ) );
        }
        for (FilterDefinition filter : definition.getFilters()) {
            def.getFilters().add( stringDef( filter ) );
        }
        return def;
    }

    private static String stringDef( PredicateDefinition predicateDefinition ) {
        return predicateDefinition.getName() + "=" + String.join(",", predicateDefinition.getArgs().values());
    }

    private static String stringDef( FilterDefinition filterDefinition ) {
        return filterDefinition.getName() + "=" + String.join("," , filterDefinition.getArgs().values());
    }


}
